import datetime

import scrapy
from flask import current_app
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

from app import evn_
from spiders.items import MarketWorkDayItem


class MarketWorkdaySpider(scrapy.Spider):
    '''
    股市工作日(上证)
    http://quote.eastmoney.com/zs000001.html
     '''
    name = 'market_workday'
    start_urls = [
        'http://quote.eastmoney.com/zs000001.html',  # 沪市

    ]

    def __init__(self, *args, **kwargs):
        chrome_options = Options()

        chrome_options.add_argument('--disable-gpu')
        chrome_options.add_argument('lang=zh_CN.UTF-8')
        chrome_options.add_argument('headless')  # 无头浏览器
        chrome_options.add_argument('--no-sandbox')  # 必要！！
        chrome_options.add_argument('--disable-dev-shm-usage')  # 必要！！
        prefs = {
            "profile.managed_default_content_settings.images": 2,  # 禁止加载图片
            'permissions.default.stylesheet': 2,  # 禁止加载css
        }
        chrome_options.add_experimental_option("prefs", prefs)
        self.bro = webdriver.Chrome(executable_path=evn_.CHROMEDRIVER_PATH, chrome_options=chrome_options)
        # self.bro = webdriver.Chrome()

    def parse(self, response):
        current_app.logger.info('{}'.format(response))
        # 大盘指数
        item = MarketWorkDayItem()

        work_day = response.xpath('//*[@id="app"]/div/div/div[6]/div/span[3]/span/text()').extract_first()
        if not work_day:
            work_day = response.xpath('//*[@id="app"]/div/div/div[6]/div/span[3]/span/span/text()').extract_first()
        current_app.logger.info('今日大盘开市状态为:{}'.format(work_day))
        if work_day:
            item['is_workday'] = 0 if work_day == '休市' else 1
            item['create_date'] = datetime.date.today()
            item['create_time'] = datetime.datetime.now()
            yield item
